'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useWeatherStore } from '@/store/weatherStore';
import {
    IconMapPin,
    IconChevronDown,
    IconSearch,
    IconGps,
    IconMenu2
} from '@tabler/icons-react';

export default function Header() {
    const router = useRouter();
    const [isDropdownOpen, setIsDropdownOpen] = useState(false);
    const [isLoading, setIsLoading] = useState(false);
    const {
        selectedCity,
        savedCities,
        setSelectedCity,
        setCurrentWeather,
        setForecasts
    } = useWeatherStore();

    // 获取地理位置
    const getCurrentLocation = () => {
        setIsLoading(true);
        if ('geolocation' in navigator) {
            navigator.geolocation.getCurrentPosition(
                async (position) => {
                    try {
                        const { latitude, longitude } = position.coords;
                        // 这里可以调用反向地理编码 API 获取城市信息
                        const response = await fetch(
                            `/api/geocode?lat=${latitude}&lon=${longitude}`
                        );
                        const cityData = await response.json();
                        setSelectedCity(cityData);
                        await fetchWeatherData(latitude, longitude);
                    } catch (error) {
                        console.error('Error getting location:', error);
                    } finally {
                        setIsLoading(false);
                    }
                },
                (error) => {
                    console.error('Error getting location:', error);
                    setIsLoading(false);
                }
            );
        }
    };

    // 获取天气数据
    const fetchWeatherData = async (lat: number, lon: number) => {
        try {
            const [weatherResponse, forecastResponse] = await Promise.all([
                fetch(`/api/weather/current?lat=${lat}&lon=${lon}`),
                fetch(`/api/weather/forecast?lat=${lat}&lon=${lon}`)
            ]);

            const weatherData = await weatherResponse.json();
            const forecastData = await forecastResponse.json();

            setCurrentWeather(weatherData);
            setForecasts(forecastData.hourly, forecastData.daily);
        } catch (error) {
            console.error('Error fetching weather data:', error);
        }
    };

    useEffect(() => {
        if (selectedCity) {
            fetchWeatherData(selectedCity.latitude, selectedCity.longitude);
        }
    }, [selectedCity]);

    return (
        <header className="sticky top-0 z-50 bg-white/80 backdrop-blur-md shadow-sm">
            <div className="container mx-auto px-4">
                <div className="h-16 flex items-center justify-between">
                    {/* 左侧菜单按钮 */}
                    <button
                        className="p-2 hover:bg-gray-100 rounded-full"
                        onClick={() => router.push('/settings')}
                    >
                        <IconMenu2 size={24} />
                    </button>

                    {/* 城市选择器 */}
                    <div className="relative flex-1 max-w-[200px] mx-4">
                        <button
                            className="w-full flex items-center justify-between px-3 py-2 bg-gray-50 rounded-full hover:bg-gray-100 transition-colors"
                            onClick={() => setIsDropdownOpen(!isDropdownOpen)}
                        >
                            <div className="flex items-center gap-2">
                                <IconMapPin size={20} />
                                <span className="truncate">
                                    {selectedCity?.name || '选择城市'}
                                </span>
                            </div>
                            <IconChevronDown
                                size={20}
                                className={`transition-transform ${isDropdownOpen ? 'rotate-180' : ''
                                    }`}
                            />
                        </button>

                        {/* 城市下拉列表 */}
                        {isDropdownOpen && (
                            <div className="absolute top-full left-0 w-full mt-2 bg-white rounded-lg shadow-lg py-2 border border-gray-100">
                                {savedCities.map((city) => (
                                    <button
                                        key={city.id}
                                        className={`w-full px-4 py-2 text-left hover:bg-gray-50 ${selectedCity?.id === city.id
                                                ? 'text-blue-600 bg-blue-50'
                                                : ''
                                            }`}
                                        onClick={() => {
                                            setSelectedCity(city);
                                            setIsDropdownOpen(false);
                                        }}
                                    >
                                        {city.name}
                                    </button>
                                ))}
                                <div className="border-t border-gray-100 mt-2 pt-2">
                                    <button
                                        className="w-full px-4 py-2 text-left text-blue-600 hover:bg-gray-50 flex items-center gap-2"
                                        onClick={() => {
                                            router.push('/cities');
                                            setIsDropdownOpen(false);
                                        }}
                                    >
                                        <IconSearch size={20} />
                                        搜索城市
                                    </button>
                                </div>
                            </div>
                        )}
                    </div>

                    {/* 定位按钮 */}
                    <button
                        className={`p-2 hover:bg-gray-100 rounded-full ${isLoading ? 'animate-spin' : ''
                            }`}
                        onClick={getCurrentLocation}
                        disabled={isLoading}
                    >
                        <IconGps size={24} />
                    </button>
                </div>
            </div>

            {/* 搜索栏 - 可以根据需要显示/隐藏 */}
            <div className="border-t border-gray-100">
                <div className="container mx-auto px-4 py-3">
                    <div className="relative">
                        <IconSearch
                            size={20}
                            className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"
                        />
                        <input
                            type="text"
                            placeholder="搜索城市、景点、地址..."
                            className="w-full pl-10 pr-4 py-2 bg-gray-50 rounded-full focus:outline-none focus:ring-2 focus:ring-blue-500 focus:bg-white"
                            onClick={() => router.push('/cities')}
                        />
                    </div>
                </div>
            </div>
        </header>
    );
}